package com.zx.flow.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.execute.common.ResponseStatusAnno;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.request.manager.ManagerFlowConfigListForm;
import com.zx.flow.api.execute.request.manager.ManagerFlowListForm;
import com.zx.flow.api.execute.response.Response;
import com.zx.flow.core.service.FlowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/manager",
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@ResponseStatusAnno
@Tag(name = "流程-管理")
public class FlowManagerController {

    @Autowired
    private FlowService flowService;

    @PostMapping("/flow/list")
    @Operation(summary = "流程-列表")
    public Response<IPage<FlowContext>> getFlowList(@RequestBody @Valid ManagerFlowListForm form) {
        return this.flowService.getFlowList(form);
    }

    @PostMapping("/config/list")
    @Operation(summary = "流程配置-列表")
    public Response<IPage<FlowConfig>> getFlowConfigList(@RequestBody @Valid ManagerFlowConfigListForm form) {
        return this.flowService.getFlowConfigList(form);
    }

    @PostMapping("/config/save")
    @Operation(summary = "流程配置-保存")
    public Response<FlowConfig> saveFlowConfig(@RequestBody FlowConfig newConfig) {
        return this.flowService.saveFlowConfig(newConfig);
    }

    @PostMapping("/config/detail")
    @Operation(summary = "流程配置-单个流程详情", parameters = {
            @Parameter(name = "flowCode", description = "流程配置编号", required = true)
    })
    public Response<FlowConfig> getFlowConfigDetail(@Valid @NotEmpty(message = "流程配置编号不能为空") String flowCode) {
        ManagerFlowConfigListForm form = new ManagerFlowConfigListForm();
        form.setFlowCode(flowCode);
        Response<IPage<FlowConfig>> result = this.flowService.getFlowConfigList(form);
        IPage<FlowConfig> data = result.getData();
        if (data == null) {
            return Response.success(null);
        }
        List<FlowConfig> records = data.getRecords();
        return CollectionUtils.isEmpty(records) ? Response.success(null) : Response.success(records.get(0));
    }

}
